Session Tracking

    The session tracking is a capability of server to maintain the current state of single client’s sequential requests. The http protocol used by web servers is stateless this means that every transaction is autonomous.
They are different ways to determine the actions that a particular client has taken. You will be examine

1. Hidden Form Fields,
2. Cookies,
3. URL Rewriting

Builtin Session Tracking functionalities found in the Servlet API.

Hidden Form Fields:-

  Using Hidden Form Fields is one of the simplest Session Tracking Technique,hidden form fields are html input types that are not displayed when read by the browser.A simple html listing that includes hidden form fields is listed in the following.

WAP on Hidden Form Fields.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Hiddenfield extends HttpServlet
{
public void init(ServletConfig conf)throws ServletException
{
Super.init(conf);
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{

response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<html> ");
pw.println("<head><title>Hidden Form Fields</title></head> ");
pw.println("<body > ");
pw.println("<form action=);
pw.println(“<input type=\”hidden\” name=”+”\”user” value=\”James\”>”);
pw.println(“<input type=\”hidden\” name=”+”\”session” value=\”1234\”>”);
pw.println(“<input type=\”hidden\” name=”+”\”movies” value=\”SOI Married on AXE Murder\”>”);
pw.println(“<input type=\”hidden\”  value=\”Finished Shoping\”>”);
pw.println(“</form>”);
pw.println("</body> ");
pw.println("</html> ");
pw.close();
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{

response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<html> ");
pw.println("<head></head> ");
pw.println("<body> ");
String user=req.getParameter(“user”);
String session=req.getParameter(“session”);
Pw.println(“<h3>”+user+”The contents of URL Shopping are=</h3><br>”);
String []movies=req.geytParameterValues(“movies”);
If(movies!=null)
{
For(int x=0;x<movies.length;x++)
{
Pw.println(movies[x]+”<br>”);
}
}
pw.println("</body> ");
pw.println("</html> ");
pw.close();
}
}
}

 

                                                                Cookies
These are introduced by Netscape.A cookies is a keyed piece of data is created by a server and stored in the client browser .Browsers maintain their own list of unique cookies. This means cookies a very viable solution for session tracking.
The servlet API provides built-in support for cookies. It does this through the use of the cookie class and Http Servlet Response. Add cookie and HttpServlet Requst ,getCookies methods.

WAP on cookies servlet?

 Import java.io.*;
Import java.util.*;
Import javax.servlet.*;
Import javax.servlet.http.*;
Public class CookieServlet extends HttpServlet
{
Public void init(ServletConfig conf)throws ServletException
{
Super.init(conf);
}
private String getCurrentUser(String value)
{
String UserName=new String(“ “);
If(value.equals(“564xxx892”))
{
UserName=new String(“Bob”);
}
Return UserName;
}
Public void doGet( HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
{
Cookie []cookielist=req.getCookies();
String user=null;
String resString=null;
If(cookielist!=null)
{
for(int x=0;x<cookielist.length;x++)
{
String name=cookielist[x].getName();
If(name.equals(“session-id”))
{
User=getCurrentUser(cookielist[x].getValue());
Break;
}
}
}
If(user==null)
{
Res.addCookie(new Cookie(“session-id”,”564xxx892”));
resString=new String(“Welcome to oursite”+”we have created a session for you”);
}
else
{
resString=new String(“Helo!”+user);
}
Res.setContentType(“text/html”);
PrintWriter pw = response.getWriter();
pw.println("<html> ");
pw.println("<head></head> ");
pw.println("<body> ");
pw.println(resString);
pw.println(“</body>”);
pw.println(“</html>”);
pw.close();
}
}

Note:
Cookies are stored in the response as http headers,therefore you must add cookies to the response before adding any other content you must have to make sure the use of cookies is ended in your browser.

                                                URL Rewriting
If your browser does not support cookies URL Rewriting provides you with another session tracking alternative. Url Rewriting is a method in which the requested URL modified yto include a sessionID. There are several ways to perform URL Rewriting.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class URLRewriting extends HttpServlet
{
public void init(ServletConfig conf)throws ServletException
{
Super.init(conf);
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{

response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<html> ");
pw.println("<head></head> ");
pw.println("<body > ");
String URL=res.encodeRedirectURL(http://localhost:8080/servlet/checkout/sid=5748);
Res.sendRedirect(URL);
pw.println("</body> ");
pw.println("</html> ");
pw.close();
}
}

Program URL rewriting

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class CounterRewrite extends HttpServlet {
  static final String COUNTER_KEY = "Counter.count";

  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
      IOException {
    HttpSession session = req.getSession(true);
    resp.setContentType("text/html");
    PrintWriter out = resp.getWriter();
    int count = 1;
    Integer i = (Integer) session.getAttribute(COUNTER_KEY);
    if (i != null) {
      count = i.intValue() + 1;
    }
    session.setAttribute(COUNTER_KEY, new Integer(count));
    out.println("<html>");
    out.println("<head>");
    out.println("<title>Session Counter</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("Your session ID is <b>" + session.getId());
    out.println("</b> and you have hit this page <b>" + count
        + "</b> time(s) during this browser session");

    String url = req.getRequestURI();
    out.println("<form method=GET action=\"" + resp.encodeURL(url) + "\">");
    out.println("<input type=submit " + "value=\"Hit page again\">");
    out.println("</form>");
    out.println("</body>");
    out.println("</html>");
    out.flush();
  }
}

Program on Hit Counter servlet
This servlet uses session tracking to count the number of times a client has accessed it. The servlet also displays all the bindings for the current session.

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
 
public class SessionTracker extends HttpServlet {
 
  public void doGet(HttpServletRequest req, HttpServletResponse res)
                               throws ServletException, IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
 
    // Get the current session object, create one if necessary
    HttpSession session = req.getSession();
 
    // Increment the hit count for this page. The value is saved
    // in this client's session under the name "tracker.count".
    Integer count = (Integer)session.getAttribute("tracker.count");
    if (count == null)
      count = new Integer(1);
    else
      count = new Integer(count.intValue() + 1);
    session.setAttribute("tracker.count", count);
 
    out.println("<HTML><HEAD><TITLE>SessionTracker</TITLE></HEAD>");
    out.println("<BODY><H1>Session Tracking Demo</H1>");
 
    // Display the hit count for this page
    out.println("You've visited this page " + count +
      ((count.intValue() == 1) ? " time." : " times."));
 
    out.println("<P>");
 
    out.println("<H2>Here is your session data:</H2>");
    Enumeration enum = session.getAttributeNames();
    while (enum.hasMoreElements()) {
      String name = (String) enum.nextElement();
      out.println(name + ": " + session.getAttribute(name) + "<BR>");
    }
    out.println("</BODY></HTML>");
  }
}

 

Program on cookie Reader

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieReader extends HttpServlet {

  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, java.io.IOException {

    Cookie cookie = null;
    //Get an array of Cookies associated with this domain
    Cookie[] cookies = request.getCookies();
    boolean hasCookies = false;

    if (cookies != null)
      hasCookies = true;

    // display the name/value of each cookie
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();

    out.println("<html>");
    out.println("<head>");
    out.println("<title>Cookie information</title>");
    out.println("</head>");
    out.println("<body>");
    if (hasCookies) {
      out.println("<h2> The name and value of each found cookie</h2>");
      for (int i = 0; i < cookies.length; i++) {
        cookie = cookies[i];
        out.println("Name of cookie #" + (i + 1) + ": "
            + cookie.getName() + "<br>");
        out.println("Value of cookie #" + (i + 1) + ": "
            + cookie.getValue() + "<br><br>");

      }
    } else {
      out.println("<h2> This request did not include any cookies</h2>");
    }

    out.println("</body>");
    out.println("</html>");

    out.close();
  }

  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, java.io.IOException {

    doGet(request, response);
  }
}

 

Use cookies to save the session Data

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ShoppingCartViewerCookie extends HttpServlet {

  public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
      IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    String sessionid = null;
    Cookie[] cookies = req.getCookies();
    if (cookies != null) {
      for (int i = 0; i < cookies.length; i++) {
        if (cookies[i].getName().equals("sessionid")) {
          sessionid = cookies[i].getValue();
          break;
        }
      }
    }

    // If the session ID wasn't sent, generate one.
    // Then be sure to send it to the client with the response.
    if (sessionid == null) {
      sessionid = generateSessionId();
      Cookie c = new Cookie("sessionid", sessionid);
      res.addCookie(c);
    }

    out.println("<HEAD><TITLE>Current Shopping Cart Items</TITLE></HEAD>");
    out.println("<BODY>");

    // Cart items are associated with the session ID
    String[] items = getItemsFromCart(sessionid);

    // Print the current cart items.
    out.println("You currently have the following items in your cart:<BR>");
    if (items == null) {
      out.println("<B>None</B>");
    } else {
      out.println("<UL>");
      for (int i = 0; i < items.length; i++) {
        out.println("<LI>" + items[i]);
      }
      out.println("</UL>");
    }

    // Ask if they want to add more items or check out.
    out.println("<FORM ACTION=\"/servlet/ShoppingCart\" METHOD=POST>");
    out.println("Would you like to<BR>");
    out.println("<INPUT TYPE=SUBMIT VALUE=\" Add More Items \">");
    out.println("<INPUT TYPE=SUBMIT VALUE=\" Check Out \">");
    out.println("</FORM>");

    // Offer a help page.
    out.println("For help, click <A HREF=\"/servlet/Help"
        + "?topic=ShoppingCartViewerCookie\">here</A>");

    out.println("</BODY></HTML>");
  }

  private static String generateSessionId() throws UnsupportedEncodingException {
    String uid = new java.rmi.server.UID().toString(); // guaranteed unique
    return URLEncoder.encode(uid,"UTF-8"); // encode any special chars
  }

  private static String[] getItemsFromCart(String sessionid) {
    return new String[]{"a","b"};  
  }
}